// pages/home/home.js
// 节流
const throttle = (fn, delay) => {
  let last
  let timer
  var delay = delay || 200
  return function () {
    let that = this
    let now = +new Date()
    if (last && now - last < delay) {
      //showToast('请勿频繁操作!','none',delay)
      clearTimeout(timer)
      timer = setTimeout(function () {
        last = now;
        fn.apply(that, arguments)
      }, delay)
    } else {
      // 第一次立即执行
      last = now
      fn.apply(that, arguments)
      // 一次操作后不再进行后续 定时器中操作
      clearTimeout(timer)
    }
  }
}

const Util = require('../../utils/util');
var isShowingPage = true;
var deviceFound = false; //是否已找到设备
var deviceCommunicating = false; //设备正在通信

Page({

  /**
   * 页面的初始数据
   */
  data: {
    headerImgUrl: '/images/ic_bg_streeting.jpg',
    adjustStreeingStatus: 0,
    selectModuleIndex: -1,
    canOperateSteeringWheel: false,
    canOperateSeat: false,
    sliderSize: 16,
    sliderActiveColor: '#007BFF',
    sliderBackgroundColor: '#212123',
    steeringWheelTempMin: 35,
    steeringWheelTempMax: 45,
    steeringWheelTempSet: 0,
    steeringWheelTemp: 0,
    seatTempMin: 35,
    seatTempMax: 45,
    seatTempSet: 0,
    seatTemp: 0,
    seatFanMin: 50,
    seatFanMax: 90,
    seatFanSet: 0,
    strengthNum: 0,
    strengthMin: 35,
    strengthMax: 49,
    massageStatus: 0, //按摩模式 0:初始化, 1:脉冲，2:波浪，3:猫步, 4:单排, 5:蝶形, 6:腰部
    blueToothName: 'SHMX-SET9', //蓝牙设备名称
    blueToothDeviceId: '', //蓝牙设备id
    serviceId: '',
    characteristicId: '',
    communicating: false, //正在连接蓝牙通信
    seatStatus: 0,
    connectCount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this;
    wx.onBluetoothAdapterStateChange(function (res) {
      console.log(res);
      deviceCommunicating = false;
      if (_this.isShowingPage) {
        if (res && res.discovering) {
          if (res.available) {
            _this.startConnectDevices();
          } else {
            _this.showBluetoothClose();
          }
        }
        _this.data.communicating = false;
        if (res.connected == false && _this.data.blueToothDeviceId != '') {
          _this.data.communicating = false;
          _this.setData({
            massageStatus: 0
          });
        }
      }

    });
  },

  showBluetoothClose() {
    // Util.showCommonModal('温馨提示', '检测到您的手机蓝牙功能已关闭，请打开手机蓝牙后再试，谢谢!', res => {});
  },

  // 节流函数的封装
  // throttle(fn, interval) {
  //   let lastCall = 0;
  //   return function (...args) {
  //     const now = Date.now();
  //     if (now - lastCall >= interval) {
  //       lastCall = now;
  //       fn.apply(this, args); // 每隔 interval 时间执行一次
  //     }
  //   };
  // },

  onAdjustSwitch: throttle(function (e) {
    if (e) {
      let index = e.currentTarget.dataset.index;
      this.selectBluetoothDevice(index);
    }
  }, 3000),

  selectBluetoothDevice(index) {
    let _this = this;
    let {blueToothDeviceId,selectModuleIndex} = _this.data;
    console.log('是否在通信:' + deviceCommunicating);
    console.log('selectModuleIndex:' + selectModuleIndex);
    
    if (selectModuleIndex == 1) {
      _this.writeToDevice('M00')
      //_this.writeToDevice('F00')
      //_this.writeToDevice('S00')
      // setTimeout(() => {
        
      // },100)
      // setTimeout(() => {
        
      // },200)
    }
    _this.writeToDevice('H00');
     
    console.log('index='+index)
    _this.setData({
      selectModuleIndex: index,
      canOperateSteeringWheel: index == 0,
      canOperateSeat: index == 1,
      headerImgUrl: index == 0 ? '/images/ic_bg_streeting.jpg' : '/images/ic_bg_seat.jpg',
      blueToothName: index == 0 ? 'SHMX-SET9' : 'HC-08',
      steeringWheelTemp: 0,
      steeringWheelTempSet: 0,
      seatTemp: 0,
      seatTempSet: 0,
      seatFanSet: 0,
      strengthNum: 0,
      adjustStreeingStatus: 0,
      massageStatus: 0,
      seatStatus: 0,
      communicating: false
    });
    setTimeout(() => {
      _this.startFindBluetooth();
    },1000)
   
    // wx.navigateTo({
    //   url: '/pages/bluetooth/bluetooth?index=' + index,
    // })
  },

  /**
   * 如果在连接过程中切换模式要先断开连接
   */
  startFindBluetooth() {
    let _this = this;
    console.log(_this.data.blueToothName)
    deviceFound = false;
    const deviceId = _this.data.blueToothDeviceId;
    console.log('deviceId=' + deviceId)
    if (deviceId && deviceId.length > 0) {
      console.log('断开连接')
      wx.closeBLEConnection({
        deviceId: deviceId,
        success: function (res) { //连接成功
          console.log('断开连接成功')
          deviceCommunicating = false;
          _this.checkLocation();
        },
        fail: function (res) { // 连接蓝牙失败
          console.log('断开连接失败')
        },
        complete() {
          // Util.hideLoading();
        }
      });
    } else {
      _this.checkLocation();
    }
  },

  checkLocation() {
    console.log('开始寻址蓝牙设备')
    let _this = this;
    _this.setData({
      blueToothDeviceId: ''
    });
    if (!deviceFound && !deviceCommunicating) {
      _this._discoveryStarted = false;
      Util.showLoading('正在初始化...');
      wx.getSetting({
        success(res) {
          Util.hideLoading();
          if (res.authSetting['scope.userLocation']) {
            _this.checkBluetooth();
          } else {
            _this.authorizeLocation();
          }
        }
      });
    }
  },

  authorizeLocation() {
    let _this = this;
    wx.authorize({
      scope: 'scope.userLocation',
      success() {
        _this.checkBluetooth();
      },
      fail(errMsg) {
        _this.authorizeLocationFail();
      }
    })
  },

  authorizeLocationFail() {
    Util.showFail('位置授权失败');
  },

  openSetting(index) {
    let _this = this;
    wx.openSetting({
      success: res => {
        if (index == 'location') {
          if (res.authSetting['scope.userLocation'] || res.authSetting['scope.userLocationBackground']) {
            _this.checkBluetooth();
          } else {
            _this.authorizeLocationFail();
          }
        } else if (index == 'bluetooth') {
          if (res.authSetting['scope.bluetooth']) {
            _this.checkBluetooth();
          } else {
            _this.authorizeBluetoothAdapter('蓝牙权限未授权');
          }
        }
      },
      fail: err => {
        if (index == 'location') {
          _this.authorizeLocationFail();
        } else if (index == 'bluetooth') {
          _this.authorizeBluetoothAdapter('蓝牙权限未授权');
        }
      }
    });
  },

  authorizeBluetoothAdapter(errMsg) {
    let _this = this;
    Util.showFail(errMsg)
  },

  checkBluetooth: function () {
    let _this = this;
    let statusMeg = '正在检查手机蓝牙...';
    Util.showLoading(statusMeg);
    wx.openBluetoothAdapter({
      success: function (res) {
        Util.hideLoading();
        _this.startBluetoothDevicesDiscovery();
      },
      fail: function (res) {
        console.log(res)
        let errMsg = res.errMsg;
        Util.hideLoading();
        if (res.errCode === 10001) {
          _this.showBluetoothClose();
        } else {
          _this.authorizeBluetoothAdapter(errMsg);
        }
      }
    });
  },

  onCheckBluetoothStatusChange() {
    let _this = this;
    wx.onBluetoothAdapterStateChange(function (res) {
      // if (!_this.isHidePage) {
      //   if (res && res.available) {
      //     _this.setData({
      //       available: res.available
      //     });
      //     if (!res.discovering && !_this._discoveryStarted) {
      //       _this.checkBluetooth();
      //     }
      //   } else {
      //     _this.showBluetoothClose();
      //   }
      // }
    });
  },

  showBluetoothClose() {
    let _this = this;
    _this._discoveryStarted = false;
    let msg = '检测到您的手机蓝牙功能未开启，请打开手机蓝牙后再试，谢谢!';
    //Util.showCommonModal('温馨提示', msg, res => {});
  },

  startBluetoothDevicesDiscovery() {
    let _this = this;
    let statusMeg = '正在搜索目标设备...';
    deviceFound = false;
    deviceCommunicating = false;
    _this._discoveryStarted = false;
    Util.showLoading(statusMeg);
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        Util.hideLoading();
        _this.onBluetoothDeviceFound();
      },
    })
  },

  onBluetoothDeviceFound() {
    let _this = this;
    _this._discoveryStarted = true;
    let {selectModuleIndex} = _this.data;
    let targetDeviceName = _this.data.blueToothName;
    console.log('targetDeviceName=' + targetDeviceName);
    console.log('selectModuleIndex=' + selectModuleIndex);
    wx.onBluetoothDeviceFound((res) => {
      if (!deviceFound && !deviceCommunicating) {
        let devices = res.devices;
        if (devices && devices.length > 0) {
          for (let i = 0; i < devices.length; i++) {
            const device = devices[i];
            if (!device.name && !device.localName) {
              deviceCommunicating = false;
              deviceFound = false;
              console.log('000:' + deviceFound)
              return
            }
            if (device.name == targetDeviceName) {
              _this.onFindDevice(device);
              break;
            }
          }
        }
      }

    })
  },

  onFindDevice(device) {
    deviceFound = true;
    this.onStopBluetoothDevicesDiscovery();
    this.setData({
      blueToothDeviceId: device.deviceId,
      blueToothName: device.name
    });
    this.startConnectDevices();
  },

  onStopBluetoothDevicesDiscovery() {
    console.log('找到目标了，停止搜索蓝牙设备')
    wx.stopBluetoothDevicesDiscovery({
      complete: () => {}
    });
  },

  onSelectBluetoothDevice(name, deviceId) {
    // wx.setNavigationBarTitle({
    //   title: name,
    // })
    this.setData({
      blueToothDeviceId: deviceId,
     // blueToothName: name
    });
    this.startConnectDevices();
  },

  startConnectDevices() {
    console.log('deviceFound=' + deviceFound)
    let that = this;
    let {
      blueToothDeviceId,
      communicating
    } = that.data;
    let deviceId = blueToothDeviceId;
    // if (!deviceId || deviceId == '') {
    //   Util.showFail('暂无发现有蓝牙设备连接，无法通信!');
    //   return
    // }
    if (!deviceCommunicating) {
      Util.showLoading('正在努力连接中...')
      wx.createBLEConnection({
        deviceId: deviceId,
        success: function (res) {
          that.getBLEDeviceServices(deviceId);
        },
        fail: function (err) {
          that.handleError();
        },
        complete() {
          Util.hideLoading();
        }
      });
    }
  },

  getBLEDeviceServices(deviceId) {
    let that = this;
    // 获取蓝牙设备service值
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function (res) {
        that.getCharacter(deviceId, res.services);
      },
      fail: function (err) {
        console.log("getBLEDeviceServices fail", err);
        // Util.showCommonModal('获取服务失败', '失败原因：' + JSON.stringify(err) + ',需要重新连接吗？', res => {
        //   if (res.confirm) {
        //     console.log('用户点击确定');
        //     that.startConnectDevices();
        //   } else if (res.cancel) {
        //     console.log('用户点击取消')
        //   }
        // })
        that.handleError();
      }
    })
  },

  getCharacter(deviceId, services) {
    let that = this;
    if (services.length <= 0) {
      // Util.showCommonModal('温馨提示', '未找到主服务列表,需要重新连接吗？', res => {
      //   if (res.confirm) {
      //     that.startConnectDevices();
      //   }
      // })
      that.handleError();
    }
    services.forEach(function (value, index, array) {
      let uuid = array[index].uuid;
      console.log('getCharacter uuid:' + uuid);
      if (uuid.indexOf('FFE0') != -1) {
        that.data.serviceId = array[index].uuid;
      }
    });
    let serviceId = that.data.serviceId;
    if (serviceId && serviceId != '') {
      that.queryBLEDeviceCharacteristics(deviceId, serviceId);
    } else {
      // Util.showCommonModal('温馨提示', '未找到主服务列表,需要重新连接吗？', res => {
      //   if (res.confirm) {
      //     console.log('用户点击确定');
      //     that.startConnectDevices();
      //   } else if (res.cancel) {
      //     console.log('用户点击取消')
      //   }
      // })
      that.handleError();
    }
  },

  queryBLEDeviceCharacteristics(deviceId, serviceId) {
    let that = this;
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: function (res) {
        let characteristics = res.characteristics;
        console.log(characteristics)
        if (characteristics && characteristics.length > 0) {
          that.handleCharacteristics(characteristics);
        } else {
          //Util.showFail('抱歉，该设备暂无服务的特征值，无法通信');
        }
      },
      fail: function (err) {
        // Util.showCommonModal('获取特性失败', '失败原因：' + JSON.stringify(err) + ',需要重新连接吗？', res => {
        //   if (res.confirm) {
        //     that.startConnectDevices();
        //   }
        // })
        that.handleError();
      },
      complete: function () {

      }
    })
  },

  handleError() {
    let that = this;
    let {
      connectCount,
      communicating
    } = that.data;
    that.setData({
      communicating: false
    })
    if (connectCount < 10) {
      // connectCount += 1;
      that.setData({
        connectCount: connectCount + 1,
      })
      // that.startConnectDevices();
    } else {
      // Util.showCommonModal('接失败', '方向盘蓝牙名称：SHMX-SET9, 座椅蓝牙名称：HC-08', res => {
      //   if (res.confirm) {
      //     that.startConnectDevices();
      //   }
      // })
      that.startConnectDevices();
    }
  },

  handleCharacteristics(mlist) {
    let that = this;
    let characteristicId = mlist[0].uuid;
    that.data.characteristicId = characteristicId;
    if (characteristicId && characteristicId != '') {
      that.startNotify();
    }
  },

  startNotify() {
    // Util.showSuccess('连接设备成功,正在通信中...');
    let that = this;
    let {
      blueToothDeviceId,
      serviceId,
      characteristicId,
      selectModuleIndex
    } = that.data;
    deviceCommunicating = true;
    that.data.communicating = true;
    that.writeToDevice('R00');
    wx.notifyBLECharacteristicValueChange({
      state: true,
      deviceId: blueToothDeviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      success: function (res) {
        console.log('notifyBLECharacteristicValueChange success' + res)
      }
    })
    wx.onBLECharacteristicValueChange(function (res) {
      let resultMessage = that.hexToString(res.value);
      let msgArray = resultMessage.split(";");
      console.log(msgArray);
      for (let i = 0; i < msgArray.length; i++) {
        var cmd = msgArray[i];
        if (cmd.startsWith("NTC1")) { //方向盘温度
          if (selectModuleIndex == 0) {
            cmd = cmd.substring(5);
            let num = parseInt(cmd);
            let temp = 0;
            if (num >= 3000) {
              temp = 5;
            } else {
              temp = (3000 - num) / 45 + 11
            }
            console.log('方向盘温度=' + Math.ceil(temp))
            that.setData({
              steeringWheelTemp: Math.ceil(temp),
              seatTemp:0
            });
          } else {
            console.log('方向盘温度:0')
            that.setData({
              steeringWheelTemp: 0
            });
          }
        } else if (cmd.startsWith("NTC2")) { //座椅温度
          if (selectModuleIndex == 1) {
            cmd = cmd.substring(5);
            let num = parseInt(cmd);
            let temp = 0;
            if (num >= 3000) {
              temp = 5;
            } else {
              temp = (3000 - num) / 45
            }
            console.log('座椅温度=' + Math.ceil(temp))
            that.setData({
              seatTemp: Math.ceil(temp),
              steeringWheelTemp:0
            });
          } else {
            console.log('座椅温度:0')
            that.setData({
              seatTemp: 0
            });
          }
        } else if (cmd.startsWith("OCS1")) {
          if (selectModuleIndex == 0) { //方向盘
            if (cmd == 'OCS1=0') { //放开方向盘
              that.setData({
                adjustStreeingStatus: 0
              });
            } else if (cmd == 'OCS1=1') { //握住方向盘
              that.setData({
                adjustStreeingStatus: 1
              });
            }
          } else if (selectModuleIndex == 1) { //座椅
            if (cmd == 'OCS1=0') { //离开座椅
              that.setData({
                seatStatus: 0
              });
            } else if (cmd == 'OCS1=1') { //有人坐上座椅
              that.setData({
                seatStatus: 1
              });
            }
          }
        }
      }
    })
  },

  hexToString(buf) {
    for (var a = buf, i = new DataView(a), n = "", s = 0; s < i.byteLength; s++) {
      n += String.fromCharCode(i.getUint8(s));
    }
    return n;
  },

  onHandleMassage(e) {
    let {
      index,
      text
    } = e.currentTarget.dataset;
    let _this = this;
    let {
      massageStatus,
      strengthMin,
      canOperateSeat
    } = _this.data;
    if (canOperateSeat) {
      let senddata = text;
      if (massageStatus == 0) {
        _this.setData({
          massageStatus: index,
          strengthNum: strengthMin
        })
        _this.writeToDevice(senddata);
        _this.writeToDevice('S01');
      } else {
        if (massageStatus == index) {
          _this.writeToDevice('M00');
          _this.setData({
            massageStatus: 0,
            strengthNum: strengthMin
          })
        } else {
          _this.writeToDevice('M00');
          _this.setData({
            massageStatus: index,
            strengthNum: strengthMin
          })
          _this.writeToDevice(senddata);
          _this.writeToDevice('S01');
        }
      }
    }
  },
  // 操作设备
  writeToDevice(senddata) {
    console.log('senddata:' + senddata);
    let _this = this;
    let {
      blueToothDeviceId,
      serviceId,
      characteristicId,
      communicating
    } = _this.data;
    let deviceId = blueToothDeviceId;
    // if (deviceCommunicating) {
    //    Util.showFail('未能成功连接设备，暂无法通信！')
    //   return
    // }
    if (deviceId == '' || serviceId == '' || characteristicId == '') {
      // Util.showFail('蓝牙设备参数异常，无法通信！')
      return
    }
    if (deviceCommunicating) {
      // 向蓝牙设备发送一个0x00的16进制数据
      let buffer = new ArrayBuffer(senddata.length + 2)
      let dataView = new DataView(buffer)
      for (var i = 0; i < senddata.length; i++) {
        dataView.setUint8(i, senddata.charAt(i).charCodeAt())
      }
      dataView.setUint8(senddata.length, 0x0d);
      dataView.setUint8(senddata.length + 1, 0x0a);
      wx.writeBLECharacteristicValue({
        deviceId,
        serviceId,
        characteristicId,
        value: buffer,
        success(res) {
          console.log('发送指令成功' + res)
          // Util.showSuccess('发送指令成功')
        },
        fail(err) {
          Util.showFail('发送指令失败')
          console.log('writeBLECharacteristicValue err:' + JSON.stringify(err))
        },
        complete() {}
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.isShowingPage = false;
  },

  onShow() {
    this.isShowingPage = true;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.closeBLEConnection();
    // wx.offBluetoothAdapterStateChange();
  },

  /**
   * 调节方向盘
   */
  changeStreetWeelTemp(e) {
    let value = e.detail.value;
    let {
      steeringWheelTempMin
    } = this.data;
    this.setData({
      steeringWheelTempSet: value
    })
    let temp = parseInt(value);
    if (temp == steeringWheelTempMin) {
      this.writeToDevice('H00');
    } else {
      let data1 = value - steeringWheelTempMin + 1;
      let senddata = "";
      if (data1 > 0 && data1 < 10) {
        senddata = "H0" + data1;
      } else {
        senddata = "H" + data1;
      }
      this.writeToDevice(senddata);
    }
  },

  /**
   * 座椅通风
   * @param {*} e 
   */
  changeSeatFan(e) {
    let value = e.detail.value;
    let {
      seatTempMin
    } = this.data;
    this.setData({
      seatFanSet: value
    })
    let temp = parseInt(value / 10);
    if (temp == 5) {
      this.writeToDevice('F00');
    } else {
      this.writeToDevice('H00');
      this.setData({
        seatTempSet: seatTempMin
      })
      let data1 = parseInt(value / 10) - 4;
      let senddata = "";
      if (data1 > 0 && data1 < 10) {
        senddata = "F0" + data1;
      } else {
        senddata = "F" + data1;
      }
      this.writeToDevice(senddata);
    }
  },

  /**
   * 座椅加热
   * @param {*} e 
   */
  changeSeatHot(e) {
    let value = e.detail.value;
    let {
      seatTempMin,
      seatFanMin
    } = this.data;
    this.setData({
      seatTempSet: value
    })
    let temp = parseInt(value);
    if (temp == seatTempMin) {
      this.writeToDevice('H00');
    } else {
      this.writeToDevice('F00');
      this.setData({
        seatFanSet: seatFanMin
      })
      let data1 = value - seatTempMin + 1;
      let senddata = "";
      if (data1 > 0 && data1 < 10) {
        senddata = "H0" + data1;
      } else {
        senddata = "H" + data1;
      }
      this.writeToDevice(senddata);
    }
  },

  /**
   * 摩擦力度
   * @param {*} e 
   */
  changeStrength(e) {
    let value = e.detail.value;
    this.setData({
      strengthNum: value
    })
    let data1 = parseInt((value - 33) / 2);
    let senddata = "";
    if (data1 < 10) {
      senddata = "S0" + data1;
    } else {
      senddata = "S" + data1;
    }
    this.writeToDevice(senddata);
  },

  /**
   * 加热方向盘
   */
  doHotSteering() {
    let {
      canOperateSteeringWheel,
      steeringWheelTempSet,
      steeringWheelTempMin
    } = this.data;
    if (canOperateSteeringWheel) {
      let senddata = "H01";
      if (steeringWheelTempSet > steeringWheelTempMin) {
        senddata = "H00";
      } else {
        steeringWheelTempMin += 1;
      }
      this.setData({
        steeringWheelTempSet: steeringWheelTempMin
      });
      this.writeToDevice(senddata);
    }
  },

  /**
   * 开始通风
   */
  doFan() {
    let {
      canOperateSeat,
      seatFanSet,
      seatFanMin,
      seatTempMin
    } = this.data;
    if (canOperateSeat) {
      let senddata = "F01";
      if (seatFanSet > seatFanMin) {
        this.setData({
          seatFanSet: seatFanMin
        });
        senddata = "F00";
      } else {
        this.setData({
          seatFanSet: seatFanMin + 10,
          seatTempSet: seatTempMin
        });
        this.writeToDevice('H00');
      }
      this.writeToDevice(senddata);
    }
  },

  doHeatSeat() {
    let {
      canOperateSeat,
      seatTempSet,
      seatTempMin,
      seatFanMin
    } = this.data;
    if (canOperateSeat) {
      let senddata = "H01";
      if (seatTempSet > seatTempMin) {
        this.setData({
          seatTempSet: seatTempMin
        });
        senddata = "H00";
      } else {
        this.setData({
          seatTempSet: seatTempMin + 1,
          seatFanSet: seatFanMin
        });
        this.writeToDevice('F00');
      }
      this.writeToDevice(senddata);
    }
  },

  up: function () {
    this.onHandleArrowWrite('U01');
  },

  upOff: function () {
    this.onHandleArrowWrite('U00');
  },

  right() {
    this.onHandleArrowWrite('B01');
  },

  rightOff() {
    this.onHandleArrowWrite('B00');
  },

  down() {
    this.onHandleArrowWrite('D01');
  },

  downOff() {
    this.onHandleArrowWrite('D00');
  },

  left() {
    this.onHandleArrowWrite('Y01');
  },

  leftOff() {
    this.onHandleArrowWrite('Y00');
  },

  onHandleArrowWrite(sendData) {
    let _this = this;
    let {
      massageStatus
    } = _this.data;
    if (massageStatus == 0) {
      _this.writeToDevice(sendData);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})